package com.zrspring.libv2.view.adview;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


//import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.zrspring.libv2.R;
import com.zrspring.libv2.util.LogUtil;
import com.zrspring.libv2.view.adview.core.ADLoopViewPager;
import com.zrspring.libv2.view.adview.core.ADPageAdapter;
import com.zrspring.libv2.view.adview.core.ADPageChangeListener;
import com.zrspring.libv2.view.adview.core.ViewPagerScroller;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 请填写作者名
 * @Encoding:UTF-8
 * @ClassName: ADview
 * @Description: 广告展示ADview
 * @date 2015年9月30日 下午8:29:46
 * @ConputerUserName zrspring
 *
 *  本广告控件借鉴与 https://github.com/imbryk/LoopingViewPager
 */

public class ADview extends LinearLayout {

    private static final String TAG = ADview.class.getSimpleName();

//    private SlidingMenu slidingMenu;

    /**
     * @Encoding:UTF-8
     * @ClassName: PageIndicatorAlign
     * @Description: 方向枚举
     * @date 2015年9月29日 下午2:31:33
     * @ConputerUserName zrspring
     */
    public enum PageIndicatorLocation {
        ALIGN_PARENT_LEFT, ALIGN_PARENT_RIGHT, CENTER_HORIZONTAL
    }

    /**
     * @Variables mDatas : AD实体的集合
     */
    private List<ADViewEntity> mDatas;

    /**
     * @Variables page_indicatorId :广告圆点的资源文件
     */
    //private int[] page_indicatorId;

    /**
     * @Variables mPointViews :广告栏下的小点
     */
    private ArrayList<ImageView> mPointViews;

    /**
     * @Variables pageChangeListener :页面切换监听
     */
    public ADPageChangeListener pageChangeListener;
    /**
     * @Variables pageAdapter : TODO(用一句话描述这个变量表示什么)
     */
    private ADPageAdapter pageAdapter;
    /**
     * @Variables viewPager : TODO(用一句话描述这个变量表示什么)
     */
    private ADLoopViewPager viewPager;
    /**
     * @Variables loPageTurningPoint :ViewGroup容器，存放ViewPager 和广告点
     */
    private ViewGroup loPageTurningPoint;
    /**
     *
     * */
    private TextView tvCountNumbers;

    /**
     * @Variables autoScrollSpacingTime :滚动间隔时间
     */
    private long autoScrollSpacingTime = 3 * 1000;
    /**
     * @Variables turning :滚动中
     */
    private boolean turning;
    /**
     * @Variables canTurn : 页面是否在滚动
     */
    private boolean canTurn = false;
    /**
     * @Variables manualPageable : 是否页面被触摸
     */
    // private boolean manualPageable = true;
    /**
     * @Variables pageindicatorSrc : 默认的引导标
     */
    private int[] pageindicatorSrc = new int[]{R.drawable.ad_page_indicator, R.drawable.ad_page_indicator_focused};

    /**
     * @Fields timeHandler :
     */
    private Handler timeHandler = new Handler();
    /**
     * @Fields adSwitchTask : 自动滚动线程
     */
    private Runnable adSwitchTask = new Runnable() {
        @Override
        public void run() {
            if (viewPager != null && turning) {
                int page = viewPager.getCurrentItem() + 1;
                viewPager.setCurrentItem(page);
                timeHandler.postDelayed(adSwitchTask, autoScrollSpacingTime);
            }
        }
    };

    /**
     * Title: Description:构造器
     *
     * @param context
     */
    public ADview(Context context) {
        this(context, null);
    }

    /**
     * Title: Description:
     *
     * @param context
     * @param attrs
     */
    public ADview(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    /**
     * @param context
     * @throws
     * @Title: init
     * @Description: 初始化View View套嵌的ViewPager
     */
    private void init(Context context) {
        if (isInEditMode()) {
            return;
        }
        View hView = LayoutInflater.from(context).inflate(
                R.layout.ad_include_viewpager, this, true);
        viewPager = (ADLoopViewPager) hView.findViewById(R.id.cbLoopViewPager);
        loPageTurningPoint = (ViewGroup) hView.findViewById(R.id.loPageTurningPoint);
        tvCountNumbers = (TextView) hView.findViewById(R.id.ad_view_count_numbers);
        if (mPointViews == null) {
            mPointViews = new ArrayList<>();
        } else {
            mPointViews.clear();
        }
        initViewPagerScroll();
    }

    /**
     * @MethodthName: setADClick
     * @params: [clickListener]
     * @Return:void
     * @Throw:
     * @Description: 设置广告的点击事件
     */
    public void setADClick(ADItemClickListener clickListener) {
        pageAdapter.setDivewClickListener(clickListener);
    }

    /**
     * @param datas
     * @return
     * @throws
     * @Title: setPages
     * @Description:设置广告的数据
     */
    public void setPages(List<ADViewEntity> datas) {
        this.mDatas = datas;
        pageAdapter = new ADPageAdapter(mDatas);
        viewPager.setAdapter(pageAdapter);
        viewPager.setBoundaryCaching(true);
        if (pageindicatorSrc != null) {
            setPageIndicator(pageindicatorSrc);
        }
    }

    /**
     * @throws
     * @Title: notifyDataSetChanged
     * @Description: 通知数据变化
     */
    public void notifyDataSetChanged() {
        viewPager.getAdapter().notifyDataSetChanged();
        if (pageindicatorSrc != null) {
            setPageIndicator(pageindicatorSrc);
        }
    }

    /**
     * @param visible
     * @throws
     * @Title: setPointViewVisible
     * @Description: 设置底部指示器是否可见
     */
    public void setPointViewVisible(boolean visible) {
        loPageTurningPoint.setVisibility(visible ? View.VISIBLE : View.GONE);
    }


    /**
     * @param visible
     * @throws
     * @Title: setPointViewVisible
     * @Description: 设置统计数目的View是否显示
     */
    public void setCountViewVisible(boolean visible) {
        tvCountNumbers.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    /**
     * @param page_indicatorId
     * @throws
     * @Title: setPageIndicator
     * @Description: 底部指示器资源图片
     */
    public void setPageIndicator(int[] page_indicatorId) {
        if (mDatas != null) {
            loPageTurningPoint.removeAllViews();
            mPointViews.clear();
            this.pageindicatorSrc = page_indicatorId;
            ImageView pointView;
            for (int count = 0; count < mDatas.size(); count++) {
                // 翻页指示的点
                pointView = new ImageView(getContext());
                pointView.setPadding(1, 0, 1, 0);
                if (mPointViews.isEmpty()) {
                    pointView.setImageResource(page_indicatorId[1]);
                } else {
                    pointView.setImageResource(page_indicatorId[0]);
                }
                mPointViews.add(pointView);
                loPageTurningPoint.addView(pointView);
            }
            pageChangeListener = new ADPageChangeListener(mPointViews, page_indicatorId, tvCountNumbers);
            tvCountNumbers.setText("1/" + mPointViews.size());
            viewPager.setOnPageChangeListener(pageChangeListener);
            //默认中心
            setPageIndicatorLocation(PageIndicatorLocation.CENTER_HORIZONTAL);
        }
    }

    /**
     * 指示器的在屏幕的位置
     * <p/>
     * <p/>
     * align
     * 居左 （RelativeLayout.ALIGN_PARENT_LEFT），
     * 居中（RelativeLayout.CENTER_HORIZONTAL），
     * 居右（RelativeLayout.ALIGN_PARENT_RIGHT）
     *
     * @return
     */
    public void setPageIndicatorLocation(PageIndicatorLocation lcation) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) loPageTurningPoint
                .getLayoutParams();
        layoutParams
                .addRule(
                        RelativeLayout.ALIGN_PARENT_LEFT,
                        lcation == PageIndicatorLocation.ALIGN_PARENT_LEFT ? RelativeLayout.TRUE
                                : 0);
        layoutParams
                .addRule(
                        RelativeLayout.ALIGN_PARENT_RIGHT,
                        lcation == PageIndicatorLocation.ALIGN_PARENT_RIGHT ? RelativeLayout.TRUE
                                : 0);
        layoutParams
                .addRule(
                        RelativeLayout.CENTER_HORIZONTAL,
                        lcation == PageIndicatorLocation.CENTER_HORIZONTAL ? RelativeLayout.TRUE
                                : 0);
        loPageTurningPoint.setLayoutParams(layoutParams);
    }

    /***
     * 是否开启了翻页
     *
     * @return
     */
    public boolean isTurning() {
        return turning;
    }

    /***
     * 开始翻页
     * autoTurningTime自动翻页时间
     *
     * @param
     * @return
     */
    public void startScroll() {
        //没有数据就抛异常
        if (mDatas != null) {
            //如果只有大于1个数据才滚动
            if (mDatas.size() > 1) {
                // 如果是正在翻页的话先停掉
                if (turning) {
                    stopScroll();
                }
                turning = true;
                canTurn = true;
                timeHandler.postDelayed(adSwitchTask, autoScrollSpacingTime);
            } else {
                //如果只有一页就不接受Touch事件
                viewPager.setCanScroll(false);
            }
        } else {
            Log.i(TAG, "startScroll: before start scroll you must call function setPages() ");
        }
    }

    /**
     * @throws
     * @Title: stopScroll
     * @Description: Adview停止滚动
     */
    public void stopScroll() {
        if (mDatas != null) {
            turning = false;
            canTurn = false;
            timeHandler.removeCallbacks(adSwitchTask);
        }
    }

    /**
     * @param newSpacingTime
     * @throws
     * @Title: setScrollSpacingTime
     * @Description: 设置ADview滚动的间隔时间
     */
    public void setScrollSpacingTime(long newSpacingTime) {
        // 如果是正在翻页的话先停掉
        if (turning) {
            stopScroll();
        }
        turning = true;
        this.autoScrollSpacingTime = newSpacingTime;
        timeHandler.postDelayed(adSwitchTask, autoScrollSpacingTime);
    }

    /**
     * 自定义翻页动画效果，使用已存在的效果
     *
     * @param tfType
     * @return
     */
    public void setPageTransformer(int tfType) {
        viewPager.setPageTransformer(true,
                ADAnimationManager.getTransformer(tfType));
    }

    /**
     * @throws
     * @Title: initViewPagerScroll
     * @Description: 设置ViewPager的滑动速度
     */
    private void initViewPagerScroll() {
        try {
            Field mScroller = null;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            ViewPagerScroller scroller = new ViewPagerScroller(
                    viewPager.getContext());
            // scroller.setScrollDuration(1500);
            mScroller.set(viewPager, scroller);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * @return
     * @throws
     * @Title: isManualPageable
     * @Description:ADview是否被触摸
     */
    public boolean isManualPageable() {
        return viewPager.isCanScroll();
    }

    /**
     * @param manualPageable true 触摸 or
     * @throws
     * @Title: setManualPageable
     * @Description: 设置ADview是否为触摸状态
     */
    public void setManualPageable(boolean manualPageable) {
        viewPager.setCanScroll(manualPageable);
    }

    /**
     * 触碰，翻页停止，离开启动翻页
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (ev.getAction() == MotionEvent.ACTION_UP) {
            LogUtil.infoMessage("ADview", "ACTION_UP 准备开始滚动");
            if(!turning){
                startScroll();
            }
        } else if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            stopScroll();
        }
        return super.dispatchTouchEvent(ev);
    }

    public ADPageChangeListener getPageChangeListener() {
        return pageChangeListener;
    }

    public void setPageChangeListener(ADPageChangeListener pageChangeListener) {
        this.pageChangeListener = pageChangeListener;
    }

    /**
     * @MethodthName: clear
     * @Description: 清空ADview 引用数据释放内存
     * @params: []
     * @Return:void
     * @Throw:
     */
    public void clear() {
        this.stopScroll();
        if (loPageTurningPoint != null) {
            loPageTurningPoint.removeAllViews();
            loPageTurningPoint = null;
        }
        if (pageindicatorSrc != null) {
            pageindicatorSrc = null;
        }
        if (mDatas != null) {
            mDatas.clear();
            mDatas = null;
        }
        if (mPointViews != null) {
            mPointViews.clear();
            mPointViews = null;
        }
        if (pageChangeListener != null) {
            pageChangeListener = null;
        }
        if (pageAdapter != null) {
            pageAdapter = null;
        }
        if (viewPager != null) {
            viewPager = null;
        }
        if (loPageTurningPoint != null) {
            loPageTurningPoint = null;
        }
        if (pageindicatorSrc != null) {
            pageindicatorSrc = null;
        }
        if (timeHandler != null) {
            timeHandler.removeCallbacksAndMessages(null);
            timeHandler = null;
        }
        if (adSwitchTask != null) {
            adSwitchTask = null;
        }
    }

//    public void setSlidingMenu(final SlidingMenu slidingMenu) {
//        this.slidingMenu = slidingMenu;
//        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            public void onPageSelected(int position) {
//                switch (position) {
//                    case 0:
//                        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
//                        //slidingMenu.showMenu();
//                        break;
//                    default:
//                        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
//                        break;
//                }
//            }
//
//            public void onPageScrolled(int arg0, float arg1, int arg2) {
//            }
//
//            public void onPageScrollStateChanged(int arg0) {
//            }
//        });
//
//    }

}
